package com.falko.android.pinhead;

import java.lang.reflect.Field;

import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;

import android.content.Context;
import android.graphics.Bitmap;
import android.opengl.GLUtils;

public class Utils {

	public static int getResId(String variableName, Context context, Class<?> c) {
		try {
			Field idField = c.getDeclaredField(variableName);
			return idField.getInt(idField);
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	private static int mTextureNameWorkspace[] = new int[1];
	public static Texture loadTexture(GL10 gl, Bitmap bitmap, Texture texture) {

		assert gl != null;
		if (texture.loaded) {
			return texture;
		}

		gl.glGenTextures(1, mTextureNameWorkspace, 0);

		int error = gl.glGetError();
		assert error == GL10.GL_NO_ERROR;

		int textureName = mTextureNameWorkspace[0];

		gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);

		error = gl.glGetError();
		assert error == GL10.GL_NO_ERROR;

		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
				GL10.GL_NEAREST);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
				GL10.GL_LINEAR);

		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
				GL10.GL_CLAMP_TO_EDGE);
		gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
				GL10.GL_CLAMP_TO_EDGE);

		gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
				GL10.GL_MODULATE); // GL10.GL_REPLACE);

		GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

		error = gl.glGetError();
		assert error == GL10.GL_NO_ERROR;

		int mCropWorkspace[] = new int[4];

		mCropWorkspace[0] = 0;
		mCropWorkspace[1] = bitmap.getHeight();
		mCropWorkspace[2] = bitmap.getWidth();
		mCropWorkspace[3] = -bitmap.getHeight();

		((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D,
				GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0);

		texture.name = textureName;
		texture.width = bitmap.getWidth();
		texture.height = bitmap.getHeight();

		error = gl.glGetError();
		assert error == GL10.GL_NO_ERROR;

		texture.loaded = true;
		
		return texture;
	}
	
	public static void deleteTexture(GL10 gl, Texture texture) {
		if (texture.resource != -1 && texture.loaded) {
        	assert texture.name != -1;
            mTextureNameWorkspace[0] = texture.name;
            texture.name = -1;
            texture.loaded = false;
            gl.glDeleteTextures(1, mTextureNameWorkspace, 0);
            int error = gl.glGetError();
            assert error == GL10.GL_NO_ERROR;
        }
	}
}
